//
//  HttpManager.m
//  iosTestDemo
//
//  Created by 证联 on 2022/7/1.
//

#import "HttpManager.h"
#import "HttpUtils.h"
#import "GMSmUtils.h"
#import "GMSm4Utils.h"

@implementation HttpManager
+ (void)post:(NSString *)interfaceId encMsg:(NSString *)encMsg succeedBlock:(void (^)(NSDictionary * _Nonnull))succeed failBlock:(void (^)(NSString * _Nonnull))fail{

    NSString *urlStr=SERVER_HOST([HttpUtils path:interfaceId]);
    //1.url
    NSURL *url = [NSURL URLWithString:urlStr];
    //request
    NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:url];
    //请求模式
    [request setHTTPMethod:@"POST"];
    // 设置请求超时
    [request setTimeoutInterval:10.0f];
       //设置header
    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
       //设置body
    [request setHTTPBody:[self parameter:interfaceId encMsg:encMsg]];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
       
  
    NSURLSessionDataTask *dataTask =  [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                //容错处理
                if (error) {
                    NSLog(@"ok容错处理%@",error);
                    if(error.code == -1009){
                        NSLog(@"ok容错处理======");
                        NSString *str=@"网络开小差了,赶紧联网吧!!!";
                        fail(str);
                    }else{
                        fail(@"错误");
                    }
                    
                    return ;
                }else if(data && [data length]>0){
                    //4.解析
                //获取相应信息
             NSString *content=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                   NSLog(@"ok解析:%@",content);
                    
                    //  data 转换Dictionary
                    
        NSDictionary *jsonData =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString *sm4Key =[jsonData objectForKey:@"sm4Key"];
                    //解密
                 NSString *deSM4Key = [GMSmUtils sm2Decrypt:sm4Key privateKey:PRIVATE_KEY];
                 
                    BOOL isOK =[GMSmUtils sm2Verify:jsonData publicKey:PUBLIC_KEY key:deSM4Key];
                    if(isOK){
                        //验签成功
                        NSString *  json = [GMSm4Utils ecbDecryptText:[jsonData objectForKey:@"encMsg"] key:deSM4Key];
                        NSLog(@"ok解析88%@",json);
                        // string转data
                           NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
                           // json解析
                        NSMutableDictionary *obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
                        succeed(obj);
                    }else{
                        //验签失败
                        NSLog(@"ok验签失败");
                    }
                }else{
                    fail(@"data is null");
                }
                
    }];
        [dataTask resume];
    
}
//公参
+(NSData *)parameter:(NSString *) interfaceId encMsg:(NSString *) encMsg{
    //十六进制字符串
    NSString *sm=[HttpUtils sm4Key];
    //获取请求流水号
    NSString *reqSeqId= [HttpUtils reqSeqId];
    //获取 时间戳
    NSString *date= [HttpUtils timeStamp:@"yyyyMMddHHmmss"];
    //获取 密钥   sm2加密
    NSString *sm4Key= [ GMSmUtils sm2Encrypt:sm publicKey:PUBLIC_KEY];
     //获取密文   明文sm4 加密
    NSString *sm4Msg = [GMSm4Utils ecbEncryptText:encMsg key:sm];
    //设置公参
    NSMutableDictionary *mutDict = [NSMutableDictionary dictionary];
       mutDict[@"encMsg"]=sm4Msg;
       mutDict[@"instuId"]=@"B00000001";
       mutDict[@"interfaceId"]=interfaceId;
       mutDict[@"reqSeqId"]=reqSeqId;
       mutDict[@"sm4Key"]=sm4Key;
       mutDict[@"timeStamp"] =date;
       mutDict[@"verNum"] = @"1.0";
        //加签
    NSString *checkValue =  [GMSmUtils sm2Sign:mutDict privateKey:PRIVATE_KEY key:sm];
       mutDict[@"checkValue"]=checkValue;
       
       NSData *json = [NSJSONSerialization dataWithJSONObject:mutDict options:NSJSONWritingPrettyPrinted error:nil];
    
//       NSString *jsonBody = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
//       NSLog(@"摘要=%@",jsonBody);
    return json;
}
@end
